package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.dialog.AuthCodeImageDialog;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.AuthStateUtils;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.SoftKeyboardUtils;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 14:42.
 * 学信网授权
 */
public class ChsiAuthActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.et_account)
    EditText etAccount;

    @BindView(R.id.et_pwd)
    EditText etPwd;

    @BindView(R.id.bt_next_step)
    Button btNextStep;

    private String userName;
    private String userPwd;
    private String taskId;

    private AuthCodeImageDialog authCodeImageDialog;
    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId=Self.Page.app_chsi_auth_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chsi_auth;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,getString(R.string.event_0x03c));
        GoogleAnalyticsUtil.setScreenName(Google.LEARN_AUTH);
    }

    @OnClick({R.id.bt_next_step,R.id.tv_agreement})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_next_step:
                SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
                if (btNextStep.getText().toString().equals("授权验证")) {
                    if (checkAccount() && checkPwd()) {
                        SelfUtils.buriedClickData(Self.Action.app_click_chsi_auth,
                                Self.Action.app_click_chsi_auth_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        userName = etAccount.getText().toString().trim();
                        userPwd = etPwd.getText().toString().trim();
                        preChsiAuth();
                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE,Google.ACTION_LEARN_AUTH);
                    }
                } else {
                    finish();
                }
                break;
            case R.id.tv_agreement:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_chsi_auth_agreement,
                        Self.Action.app_click_chsi_auth_agreement_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,
                        "学信网授权协议");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                        URLUtil.DATA_PARSER_AGREEMENT);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I,14);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
                break;
        }
    }

    @OnCheckedChanged(R.id.cb_agreement)
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
        if(buttonView.getId()==R.id.cb_agreement&&isChecked){
            btNextStep.setEnabled(true);
        }else{
            btNextStep.setEnabled(false);
        }
    }

    private boolean checkAccount(){
        boolean result=false;
        String account=etAccount.getText().toString().trim();
        if(account.length()>0){
            result=true;
        }else{
            ToastUtil.showToast("请输入账号");
        }
        return result;
    }

    private boolean checkPwd(){
        boolean result=false;
        String pwd=etPwd.getText().toString().trim();
        if(pwd.length()>0){
            result=true;
        }else{
            ToastUtil.showToast("请输入密码");
        }
        return result;
    }

    private void showAuthCodeDialog(Bitmap bitmap){
        if(authCodeImageDialog ==null){
            authCodeImageDialog =new AuthCodeImageDialog(mContext);
            authCodeImageDialog.setAuthImage(bitmap);
            authCodeImageDialog.setButtonClickedListener(new AuthCodeImageDialog.OnAuthCodeButtonClicked() {
                @Override
                public void onRefreshButtonClicked() {
                    preChsiAuth();
                }

                @Override
                public void onCommitButtonClicked(String authCode) {
                    chsiAuth(authCode);
                }
            });
            authCodeImageDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    authCodeImageDialog.callSoftKeyBoard();
                }
            });
            authCodeImageDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
                }
            });
        }else{
            authCodeImageDialog.setAuthImage(bitmap);
        }
        authCodeImageDialog.clearText();
        if(!authCodeImageDialog.isShowing()){
            authCodeImageDialog.show();
        }
    }

    private void dismissAuthCodeDialog(){
        if(authCodeImageDialog !=null&& authCodeImageDialog.isShowing()){
            authCodeImageDialog.dismiss();
        }
    }

    /**学信网授权，获取验证码，任务id等*/
    private void preChsiAuth(){
        showProgressDialog(false);
        Observable<String> observable= Api.preChsiAuth();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json= JSON.parseObject(s);
                if(json.getIntValue("code")==2005){
                    //获取验证码成功
                    taskId=json.getString("task_id");
                    byte[] bytes=Base64.decode(json.getString("authCode"),Base64.DEFAULT);
                    Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                    showAuthCodeDialog(bitmap);
                }else{
                    ToastUtil.showToast(json.getString("message"));
                }
            }
        });
    }

    /**学信网授权*/
    private void chsiAuth(String authCode){
        showProgressDialog(false);
        Map<String,Object> params=new HashMap<>();
        params.put("user_id",mApplication.getUser().getID());
        params.put("user_name",userName);
        params.put("user_pass",userPwd);
        params.put("task_id",taskId);
        params.put("auth_code",authCode);
        //action 1授权
        params.put("action",1);
        Observable<String> observable=Api.chsiAuth(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json=JSON.parseObject(s);
                int code=json.getIntValue("code");
                if(AuthStateUtils.isSuccess(code)){
                    //授权成功
                    dismissAuthCodeDialog();
                    btNextStep.setText("返回");
                    ToastUtil.showToast("授权中");
                }else{
                    ToastUtil.showToast(json.getString("message"));
                    if(code==102){
                        //验证码错误，重新获取验证码
                        preChsiAuth();
                    }else{
                        dismissAuthCodeDialog();
                    }
                }
            }
        });
    }
}
